<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false"></el-alert>
      <!-- 步骤条 active 0 1 2 3 4 5 -->
      <el-steps :active="active-0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 标签页 -->
      <el-form :model="addGoodsForm" :rules="addGoodsRules" ref="addGoodsForm" label-position="top">
        <el-tabs v-model="active" :tab-position="'left'" :before-leave="beforeLeave" @tab-click="tabClick">
          <!-- 基本信息 -->
          <el-tab-pane label="基本信息" name="0">
              <el-form-item label="商品名称" prop="goods_name">
                <el-input v-model="addGoodsForm.goods_name"></el-input>
              </el-form-item>
              <el-form-item label="商品价格" prop="goods_price">
                <el-input v-model="addGoodsForm.goods_price" type="number"></el-input>
              </el-form-item>
              <el-form-item label="商品重量" prop="goods_weight">
                <el-input v-model="addGoodsForm.goods_weight" type="number"></el-input>
              </el-form-item>
              <el-form-item label="商品数量" prop="goods_number">
                <el-input v-model="addGoodsForm.goods_number" type="number"></el-input>
              </el-form-item>
              <el-form-item label="商品分类" prop="goods_cat">
                <el-cascader v-model="addGoodsForm.goods_cat" :options="cateList" :props="cateListProps" @change="handleChange"></el-cascader>
              </el-form-item>
          </el-tab-pane>
          <!-- 商品参数 -->
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="(item) in manyCateList" :key="item.attr_id">
              <!-- 复选框 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox border :label="item" v-for="(item,i) in item.attr_vals" :key="i"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品属性 -->
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyCateList" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品图片 -->
          <el-tab-pane label="商品图片" name="3">
            <!-- 上传图片 -->
            <!-- action是后台api的地址 -->
            <el-upload
            :action="upload"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :headers="headerObj"
            :on-success="uploadSuccess"
            list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
          </el-tab-pane>
          <!-- 商品内容 -->
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addGoodsForm.goods_introduce"
            ref="myQuillEditor">
            </quill-editor>
            <el-button class="m_t" @click="addGoods" type="primary">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>

    </el-card>

    <!-- 点击图片名字弹出一个对话框 -->
      <el-dialog
      title="图片预览"
      :visible.sync="previewVisible"
      width="50%"
      @close="previewVisible=false">
      <img :src="previewPath" alt="" width="100%">
    </el-dialog>
  </div>
</template>

<script>
// Load the full build.
import _ from 'lodash'

export default {
  name: 'Add',
  created () {
    this.getCateList()
  },
  data () {
    return {
      // 步骤条--标签页 acitve=》步骤是从index 0开始
      active: '0',
      // 表单中input的值
      addGoodsForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        // 商品内容
        goods_introduce: '',
        // 图片上传tmp_path
        pics: [],
        // 包含动态参数和静态属性
        attrs: []
      },
      // 表单的校验规则
      addGoodsRules: {
        goods_name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        goods_price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        goods_weight: [{ required: true, message: '请输入商品重量', trigger: 'blur' }],
        goods_number: [{ required: true, message: '请输入商品数量', trigger: 'blur' }],
        goods_cat: [{ required: true, message: '请输入商品分类', trigger: 'blur' }]
      },
      // 商品分类列表
      cateList: [],
      // 是一个数组，是每层层级的分类cat_id的id值
      selectedKeys: [],
      cateListProps: {
        label: 'cat_name',
        // 每层分类的id
        value: 'cat_id',
        children: 'children',
        // 鼠标经过触发
        expandTrigger: 'hover'
      },
      // 商品参数
      manyCateList: [],
      // 商品属性
      onlyCateList: [],
      // 图片要上传到的后台地址
      upload: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 图片上传组件的headers请求头对象
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 是绑定到对话框img-src属性中图片地址
      previewPath: '',
      // 控制图片预览对话框显示与隐藏
      previewVisible: false,
      content: ''
    }
  },
  methods: {
    // 获取商品分类列表数据
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取分类数据失败')
      }
      this.cateList = res.data
      console.log(this.cateList)
    },
    // 选择的级联发送变化时触发
    handleChange () {
      // console.log(key)
      // 只能选择三级
      // 没选择三级就把值设置为空，还不能跳转到其他
      if (this.addGoodsForm.goods_cat.length !== 3) {
        this.addGoodsForm.goods_cat = []
      }
    },
    // 标签页发生切换之前触发
    beforeLeave (acitveName, oldActiveName) {
      console.log(oldActiveName)
      console.log(acitveName)
      if (oldActiveName !== 0 && this.addGoodsForm.goods_cat.length !== 3) {
        this.$message.error('请选择商品分类')
        return false
      }
    },
    // tab标签页被选中时触发--被选中的标签 tab 实例
    async tabClick () {
      // 是VueComponent
      if (this.active === '1') {
        // 获取商品动态参数
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: 'many' } })
        if (res.meta.status !== 200) {
          return this.$message.error('获取商品参数失败')
        }
        res.data.forEach(item => {
          if (item.attr_vals.length === 0) {
            item.attr_vals = []
          } else {
            item.attr_vals = item.attr_vals.split(' ')
          }
          // console.log(item.attr_vals.split(' '))
        })
        this.manyCateList = res.data
        console.log(this.manyCateList)
      }
      if (this.active === '2') {
        // 获取商品属性
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: 'only' } })
        if (res.meta.status !== 200) {
          return this.$message.error('获取商品参数失败')
        }
        this.onlyCateList = res.data
        console.log(this.onlyCateList)
      }
    },
    // 点击图片名字时图片预览
    handlePreview (file) {
      console.log(file)
      // 把imgsrc的地址绑定为file.response.data.url
      this.previewPath = file.response.data.url
      // 显示对话框
      this.previewVisible = true
    },
    // 移除图片文件时触发
    handleRemove (file, fileList) {
      // 把添加到addGoodsForm的pics的该文件删除
      // console.log(file)//被删除的文件
      // console.log(fileList)//剩下的是没有被删除的文件
      // this.addGoodsForm.pics = this.addGoodsForm.pics.filter(item => {
      //   return item.pic !== file.response.data.tmp_path
      // })
      // console.log(this.addGoodsForm.pics)
      // 1.找到图片的临时路径
      // 2.从pics数组中找到对应的索引值
      const i = this.addGoodsForm.pics.findIndex(item => {
        item.pic = file.response.data.tmp_path
      })
      // 3.再使用splice方法从pics数组中删除
      this.addGoodsForm.pics.splice(i, 1)
      console.log(this.addGoodsForm.pics)
    },
    // 文件上传成功时触发
    uploadSuccess (response) {
      console.log(response)
      if (response.meta.status !== 200) {
        return this.$message.error('上传图片失败')
      }
      // 上传图片成功就把值赋值给pics
      // 1.先拼接一个对象
      const picInfo = {}
      picInfo.pic = response.data.tmp_path
      // 2.把对象追加到pics数组中
      this.addGoodsForm.pics.push(picInfo)
      console.log(this.addGoodsForm)
    },
    // 点击添加商品
    addGoods () {
      // 点击要先验证表单内容
      this.$refs.addGoodsForm.validate(async valid => {
        // 验证失败返回
        if (!valid) return this.$message.error('请填写必要的表单项')
        // 验证成功
        // 深拷贝addGoodsForm--loadsh
        const goodsForm = _.cloneDeep(this.addGoodsForm)
        goodsForm.goods_cat = goodsForm.goods_cat.join(',')
        this.manyCateList.forEach(item => {
          const itemObj = { attr_id: item.attr_id, attr_value: item.attr_vals.join(' ') }
          goodsForm.attrs.push(itemObj)
        })
        this.onlyCateList.forEach(item => {
          const itemObj = { attr_id: item.attr_id, attr_value: item.attr_vals }
          goodsForm.attrs.push(itemObj)
        })
        // 点击添加商品向服务器发送请求
        const { data: res } = await this.$http.post('goods', goodsForm)
        console.log(res)
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg)
        }
        // 添加成功就跳转页面到商品列表页面/goods
        this.$router.push('/goods')
      })
      // 1.attrs添加动态参数和静态属性
      // 要深拷贝addGoodsForm
    }
  },
  computed: {
    cateId () {
      // 如果长度为3就返回最后一个分类id
      if (this.addGoodsForm.goods_cat.length === 3) {
        return this.addGoodsForm.goods_cat[2]
      }
      // 如果长度不为3就返回null
      return null
    }
  }

}
</script>

<style lang="less">
.el-steps {
  margin: 15px 0;
  font-size: 12px;
}
.el-step__title {
    font-size: 12px !important;
}
.el-tab-pane {
  font-size: 14px;
}
.el-checkbox {
  margin: 0 10px 0 0;
}
.ql-container {
  height: 300px;
}
.m_t {
  margin-top: 15px;
}
</style>
